import Vue from "vue";
import $web3js from "../web3.js";
import $usdt from "../usdt/index.js";

const ifilAbsContract = require("./ifilAbsContract.json");
let contractAddress = "";

let web3 = $web3js.getWeb3();
let contractConst = {
  contract: web3
    ? new web3.eth.Contract(ifilAbsContract.abi, contractAddress)
    : ""
};
const getIfilAbsAddress = () => {
  return contractAddress;
};

const getIfilAbsContract = () => {
  return contractConst.contract;
};

const userDeposit = async _amount => {
  _amount = await $usdt.toUsdtValue(_amount);
  return $web3js.commonSend(getIfilAbsContract().methods.userDeposit, _amount);
};

const userDepositEstimateGas = async _amount => {
  _amount = await $usdt.toUsdtValue(_amount);
  return $web3js.commonEstimateGas(
    getIfilAbsContract().methods.userDeposit,
    _amount
  );
};

const userRedeem = () => {
  return $web3js.commonSend(getIfilAbsContract().methods.userRedeem);
};

const userRedeemEstimateGas = () => {
  return $web3js.commonEstimateGas(getIfilAbsContract().methods.userRedeem);
};

const vendorWithdrawABS = _prodid => {
  return $web3js.commonSend(
    getIfilAbsContract().methods.vendorWithdraw,
    _prodid
  );
};

const vendorWithdrawABSEstimateGas = _prodid => {
  return $web3js.commonEstimateGas(
    getIfilAbsContract().methods.vendorWithdraw,
    _prodid
  );
};

const getDtokenBalance = _owner => {
  return $web3js.commonCallAndHandler(
    getIfilAbsContract().methods.balanceOf,
    $web3js.fromWei,
    _owner
  );
};

const getABSPoolInfo = () => {
  return $web3js.commonCallAndHandler(
    getIfilAbsContract().methods.getABSPoolInfo,
    handleABSPoolInfo
  );
};

const handleABSPoolInfo = async res => {
  let totalAmount = await $usdt.fromUsdtValue(res[0]);
  let liquidAmount = await $usdt.fromUsdtValue(res[1]);
  let exchangeAmount = await $usdt.fromUsdtValue(res[2]);
  let tokenPrice = Vue.prototype.$numberUtils.movePointLeft(res[3], 4);
  return {
    totalAmount,
    liquidAmount,
    exchangeAmount,
    tokenPrice
  };
};

const getProdReleaseInfo = _prodid => {
  return $web3js.commonCallAndHandler(
    getIfilAbsContract().methods.getProdReleaseInfo,
    handleABSProdReleaseInfo,
    _prodid
  );
};

const handleABSProdReleaseInfo = async res => {
  let totalLocks = await $usdt.fromUsdtValue(res[0]);
  let totalGains = await $usdt.fromUsdtValue(res[1]);
  let lockDay = res[2];
  let releaseDay = res[3];
  let avlRecv = await $usdt.fromUsdtValue(res[4]);
  let recvAddr = res[5];
  return {
    totalLocks,
    totalGains,
    lockDay,
    releaseDay,
    avlRecv,
    recvAddr
  };
};

export default {
  getIfilAbsAddress,
  getIfilAbsContract,
  userDeposit,
  userDepositEstimateGas,
  userRedeem,
  userRedeemEstimateGas,
  vendorWithdrawABS,
  vendorWithdrawABSEstimateGas,
  getDtokenBalance,
  getABSPoolInfo,
  getProdReleaseInfo
};
